package glpm

import (
	"context"
	"fmt"
	"strings"
)

// RpmManager RPM包管理器实现
type RpmManager struct {
	*BaseManager
}

// NewRpmManager 创建RPM包管理器
func NewRpmManager(config *ManagerConfig) *RpmManager {
	base := NewBaseManager("rpm", config)
	return &RpmManager{
		BaseManager: base,
	}
}

// Install 安装包
func (rm *RpmManager) Install(ctx context.Context, packages []string) error {
	if len(packages) == 0 {
		return fmt.Errorf("需要指定要安装的包文件路径")
	}
	
	args := []string{"-i"}
	args = append(args, packages...)
	
	_, err := rm.executeCommand(ctx, args...)
	return err
}

// Remove 移除包
func (rm *RpmManager) Remove(ctx context.Context, packages []string) error {
	if len(packages) == 0 {
		return fmt.Errorf("需要指定要移除的包名")
	}
	
	args := []string{"-e"}
	args = append(args, packages...)
	
	_, err := rm.executeCommand(ctx, args...)
	return err
}

// Update 更新包列表（RPM不支持更新操作）
func (rm *RpmManager) Update(ctx context.Context) error {
	return fmt.Errorf("RPM包管理器不支持更新操作")
}

// Upgrade 升级包
func (rm *RpmManager) Upgrade(ctx context.Context, packages []string) error {
	if len(packages) == 0 {
		return fmt.Errorf("需要指定要升级的包文件路径")
	}
	
	args := []string{"-U"}
	args = append(args, packages...)
	
	_, err := rm.executeCommand(ctx, args...)
	return err
}

// Search 搜索包
func (rm *RpmManager) Search(ctx context.Context, pattern string) ([]PackageInfo, error) {
	output, err := rm.executeCommand(ctx, "-qa", pattern)
	if err != nil {
		return nil, err
	}
	
	return rm.parseSearchOutput(output)
}

// Info 获取包信息
func (rm *RpmManager) Info(ctx context.Context, packageName string) (*PackageInfo, error) {
	output, err := rm.executeCommand(ctx, "-qi", packageName)
	if err != nil {
		return nil, err
	}
	
	return rm.parseInfoOutput(output)
}

// ListInstalled 列出已安装的包
func (rm *RpmManager) ListInstalled(ctx context.Context) ([]PackageInfo, error) {
	output, err := rm.executeCommand(ctx, "-qa")
	if err != nil {
		return nil, err
	}
	
	return rm.parseListOutput(output)
}

// IsInstalled 检查指定包是否已安装
func (rm *RpmManager) IsInstalled(ctx context.Context, packageName string) (bool, error) {
	output, err := rm.executeCommand(ctx, "-q", packageName)
	if err != nil {
		// 如果命令执行失败，通常表示包未安装
		return false, nil
	}
	
	// 如果输出不为空，表示包已安装
	return strings.TrimSpace(output) != "", nil
}

// parseSearchOutput 解析搜索输出
func (rm *RpmManager) parseSearchOutput(output string) ([]PackageInfo, error) {
	var packages []PackageInfo
	
	lines := strings.Split(output, "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}
		
		// 包名格式: name-version-release.architecture
		parts := strings.Split(line, "-")
		if len(parts) >= 3 {
			pkgName := parts[0]
			version := parts[1]
			releaseArch := strings.Split(parts[2], ".")
			
			if len(releaseArch) >= 2 {
				version = version + "-" + releaseArch[0]
				arch := releaseArch[1]
				
				packages = append(packages, PackageInfo{
					Name:         pkgName,
					Version:      version,
					Architecture: arch,
					Status:       "installed",
				})
			}
		}
	}
	
	return packages, nil
}

// parseInfoOutput 解析包信息输出
func (rm *RpmManager) parseInfoOutput(output string) (*PackageInfo, error) {
	info := &PackageInfo{}
	
	lines := strings.Split(output, "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		
		if strings.HasPrefix(line, "Name") {
			info.Name = strings.TrimSpace(strings.Split(line, ":")[1])
		} else if strings.HasPrefix(line, "Version") {
			info.Version = strings.TrimSpace(strings.Split(line, ":")[1])
		} else if strings.HasPrefix(line, "Architecture") {
			info.Architecture = strings.TrimSpace(strings.Split(line, ":")[1])
		} else if strings.HasPrefix(line, "Summary") {
			info.Description = strings.TrimSpace(strings.Split(line, ":")[1])
		}
	}
	
	return info, nil
}

// parseListOutput 解析列表输出
func (rm *RpmManager) parseListOutput(output string) ([]PackageInfo, error) {
	var packages []PackageInfo
	
	lines := strings.Split(output, "\n")
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}
		
		// 包名格式: name-version-release.architecture
		parts := strings.Split(line, "-")
		if len(parts) >= 3 {
			pkgName := parts[0]
			version := parts[1]
			releaseArch := strings.Split(parts[2], ".")
			
			if len(releaseArch) >= 2 {
				version = version + "-" + releaseArch[0]
				arch := releaseArch[1]
				
				packages = append(packages, PackageInfo{
					Name:         pkgName,
					Version:      version,
					Architecture: arch,
					Status:       "installed",
				})
			}
		}
	}
	
	return packages, nil
}